//
//  HOTOrenoDetailViewController.m
//  Genpara
//
//  Created by zhang chunhui on 14-9-30.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTOrenoDetailViewController.h"
#import "HOTOrenoListCell.h"
#import "HOTOrenoReplayCell.h"
#import "HOTImagePriviewer.h"

#define oreno_detail_cell_id @"orenoDetailCell"
#define oreno_comment_cell_id @"orenoCommentCell"

@interface HOTOrenoDetailViewController () <UITableViewDataSource,UITableViewDelegate>{
    
    NSInteger _pageNo;
    NSMutableDictionary *_cellCache;
}

@property(nonatomic,strong)NSMutableArray *dataList;
@property(nonatomic,copy)NSString *article_id;
@property(nonatomic,strong)NSDictionary *detailInfo;
@end

@implementation HOTOrenoDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil article_id:(NSString *)article_id articleInfo:(NSDictionary *)info
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.article_id = article_id;
        self.detailInfo = info;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_oreno"]];
    [self setNaviTitle:@"俺のシリーズ"];
    
    self.dataList = [NSMutableArray array];
    
    _cellCache = [NSMutableDictionary dictionary];
    
    __unsafe_unretained HOTOrenoDetailViewController *tempObj = self;
    
    [self showChatInputBar:YES];
    
    self.chatInputBar.sendBtnClicked = ^(NSString *sendMsg) {
        
        
        //[tempObj.chatInputBar.chatTextView resignFirstResponder];
        
        [tempObj replayClosure:sendMsg];
        
    };
    
    _tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, _tableView.frame.size.height - self.chatInputBar.frame.size.height);
    
    _tableView.showFooter = YES;
    _tableView.showHeader = YES;
    
    _tableView.headerView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        _pageNo = 1;
        [tempObj requestDataFromNet];
    };
    
    _tableView.footerView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        _pageNo ++;
        [tempObj requestDataFromNet];
    };
    
    UITapGestureRecognizer  *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTable)];
    [tgr setNumberOfTapsRequired:1];
    [tgr setNumberOfTouchesRequired:1];
    
    [_tableView addGestureRecognizer:tgr];
    
    _pageNo = 1;
    [self requestDataFromNet];
}

-(void)tapTable {

    [self.chatInputBar.chatTextView resignFirstResponder];
}

-(void)replayClosure:(NSString *)msg {
    __unsafe_unretained HOTOrenoDetailViewController *tempObj = self;
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_ARTICLE_ID:[HOTUtils getString:self.article_id],
                                 REQ_KEY_REPLAY_CONTENT:[HOTUtils getString:msg]};
    
    [self showLoading];
    [self requestWithURL:HOT_URL_MY_SERIES_INFO_REPLY Parameters:parameters success:^(NSInteger result, NSArray * dataArr) {
        
        [tempObj loadingSuccess];
        
        NSLog(@"评论成功");
        
        NSDate *curDate = [NSDate date];
        NSString *curDateStr = [ZZZUtils formartDate:curDate withStyle:@"yyyy-MM-dd hh:mm:ss"];
        int newId = 1;
        if (tempObj.dataList.count > 0) {
            newId = [[[tempObj.dataList lastObject] objectForKey:@"mock_id"] intValue];
        }
        NSDictionary *newCommon = @{
                                    @"user_id":self.userInfo.userId,
                                    @"user_nick":[HOTUtils getString:tempObj.userInfo.nick],
                                    @"city_name":@"",
                                    @"job_name":@"",
                                    @"comment_time":curDateStr,
                                    @"comment_content":[HOTUtils getString:msg]
                                    };
        [tempObj.chatInputBar.chatTextView resignFirstResponder];
        [tempObj.dataList addObject:newCommon];
        NSIndexPath *insertIndex = [NSIndexPath indexPathForRow:tempObj.dataList.count inSection:0];
        
        [tempObj->_tableView insertRowsAtIndexPaths:@[insertIndex] withRowAnimation:UITableViewRowAnimationBottom];
        
        [tempObj->_tableView scrollToRowAtIndexPath:insertIndex atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            //[popupView setOffset:CGPointMake(0, -90)];
            [popupView showInWindow];
        }
    }];
}

-(void)requestDataFromNet {
    
    [self showLoading];
    __unsafe_unretained HOTOrenoDetailViewController *tempObj = self;
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_ARTICLE_ID:[HOTUtils getString:self.article_id],
                                 REQ_KEY_P_NUM:@(_pageNo),
                                 REQ_KEY_P_SIZE:kPageCnt};

    [self requestWithURL:HOT_URL_MY_SERIES_INFO_LIST Parameters:parameters success:^(NSInteger result, NSArray * dataArr) {
        
        [tempObj loadingSuccess];
        [_tableView.headerView endRefreshing];
        [_tableView.footerView endRefreshing];
        if (dataArr.count == 0) {
            
            if (_pageNo == 1) {
                
                [tempObj.dataList removeAllObjects];
                [_tableView reloadData];
//                [self alertNoDataMessage:^{
//                    //[tempObj.navigationController popViewControllerAnimated:YES];
//                }];
            } else {
                [self alertNoDataAgainMessage:nil];
            }
            
            
            return;
        }
        
        if (_pageNo == 1) {
            [tempObj.dataList removeAllObjects];
        }
        [tempObj.dataList addObjectsFromArray:dataArr];
        
        [_tableView reloadData];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        [_tableView.headerView endRefreshing];
        [_tableView.footerView endRefreshing];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

-(void)chatBarFrameWillChange:(CGPoint)newPoint {
    
    _tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, newPoint.y);
    
    if (self.dataList.count > 0) {
        [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataList.count inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}


#pragma mark - UItableView DataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        
        static NSString *cellId = oreno_detail_cell_id;
        HOTOrenoListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        
        if (cell == nil) {
            
            //cell = [_cellCache objectForKey:@(indexPath.row)];
            

            cell = [self createDetailCellWithCellId:cellId];

        }
        
        cell.delegate = self;
        cell.indexPath = indexPath;
        [self setCell:cell dic:self.detailInfo];
        
        return cell;
    }
    static NSString *cellId = oreno_comment_cell_id;
    HOTOrenoReplayCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (cell == nil) {
        
        //cell = [_cellCache objectForKey:@(indexPath.row-1)];
        
        //if (cell == nil) {
            
            cell = [self createCommentCellWithCellId:cellId];
            
           // [_cellCache setObject:cell forKey:@(indexPath.row-1)];
        //}
    }
    
    cell.indexPath = indexPath;
    
    NSDictionary *dic = [self.dataList objectAtIndex:indexPath.row-1];
    
    [self setCommentCell:cell dic:dic];
    cell.majiLabel.user_id = [dic objectForKey:@"user_id"];
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataList.count +1;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        
        
        HOTOrenoListCell *cell = [tableView dequeueReusableCellWithIdentifier:oreno_detail_cell_id];
        
        if (cell == nil) {
            
            cell = [self createDetailCellWithCellId:oreno_detail_cell_id];
            
            //[_cellCache setObject:cell forKey:@(indexPath.row)];
        }
        
        [self setCell:cell dic:self.detailInfo];
        
        [cell setNeedsDisplay];
        [cell setNeedsUpdateConstraints];
        [cell.contentView setNeedsDisplay];
        [cell.contentView setNeedsUpdateConstraints];
        
        float cellH = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
        
//        NSLog(@"cellH = %f",cellH);
        return cellH +1;
    }
    HOTOrenoReplayCell *cell = [tableView dequeueReusableCellWithIdentifier:oreno_comment_cell_id];
    
    if (cell == nil) {
        
        cell = [self createCommentCellWithCellId:oreno_comment_cell_id];
        
        //[_cellCache setObject:cell forKey:@(indexPath.row-1)];
    }
    
    
    
    NSDictionary *dic = [self.dataList objectAtIndex:indexPath.row-1];
    
    [self setCommentCell:cell dic:dic];
    
    [cell setNeedsDisplay];
    [cell setNeedsUpdateConstraints];
    [cell.contentView setNeedsDisplay];
    [cell.contentView setNeedsUpdateConstraints];
    
    float cellH = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    
//    NSLog(@"cellH = %f",cellH);
    return cellH +1;
}

#pragma mark - UITableView Delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)setCell:(HOTOrenoListCell *)cell dic:(NSDictionary *)dic {
    
    cell.majiLabel.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"user_name"]];
    cell.placeName.text = [NSString stringWithFormat:@"【%@】%@", [dic objectForKey:@"city"],[dic objectForKey:@"job_name"]];
    cell.titleLabel.text = [dic objectForKey:@"title"];
    cell.dateTimeLabel.text = [dic objectForKey:@"article_time"];
    cell.contentLabel.text = [dic objectForKey:@"article_content"];
    
    NSURL *url = [NSURL URLWithString:[dic objectForKey:@"pic_thumb_url"]];
    if (![url isKindOfClass:[NSNull class]]) {
        [cell setContentImage:url];
    } else {
        
        [cell setContentImage:nil];
    }
}

-(void)setCommentCell:(HOTOrenoReplayCell *)cell dic:(NSDictionary *)dic {

    cell.majiLabel.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"user_nick"]];
    //cell.placeName.text = [NSString stringWithFormat:@"【%@】%@", [dic objectForKey:@"city_name"],[dic objectForKey:@"job_name"]];
    cell.userIdLab.text = [dic objectForKey:@"user_id"];
    cell.dateTimeLabel.text = [dic objectForKey:@"comment_time"];
    cell.contentLabel.text = [dic objectForKey:@"comment_content"];
}

-(HOTOrenoListCell *)createDetailCellWithCellId:(NSString *)cellId {
    
    UINib *nib = [UINib nibWithNibName:XIB(@"HOTOrenoListCell") bundle:nil];
    [_tableView registerNib:nib forCellReuseIdentifier:cellId];
    
    HOTOrenoListCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellId];
    
    return cell;
}

-(HOTOrenoReplayCell *)createCommentCellWithCellId:(NSString *)cellId {
    
    UINib *nib = [UINib nibWithNibName:XIB(@"HOTOrenoReplayCell") bundle:nil];
    [_tableView registerNib:nib forCellReuseIdentifier:cellId];
    
    HOTOrenoReplayCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellId];
    
    return cell;
}

-(void)contentImageClicked:(NSIndexPath *)clickIndexPath {
    
    NSString *urlStr = [self.detailInfo objectForKey:@"pic_url"];
    
    if ([HOTUtils isNotNullOrEmpty:urlStr]) {
        
        [[HOTImagePriviewer priviewer] showInView:[[UIApplication sharedApplication] keyWindow] withUrl:urlStr placeHolder:kImageHolder];
    } else {
        
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
